package com.ctbri.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.ctbri.util.SwingConsole;

public class Ex9 extends JFrame {
	
	private JTextField name = new JTextField(25);
	private JTextField filter = new JTextField(25);
	private JTextArea results = new JTextArea(40, 65);
	private static Pattern qualifier = Pattern.compile("\\w+\\.");
	class NameL implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			String nm = name.getText().trim();
			if(nm.length() == 0){
				results.setText("No match");
				return;
			}
			Class<?> kind;
			try {
				kind = Class.forName(nm);
			} catch (ClassNotFoundException ex) {
				results.setText("No match");
				return;
			}
			Method[] methods = kind.getMethods();
			Constructor<?>[] ctors = kind.getConstructors();
			results.setText("");
			String filterStr = filter.getText().trim();
			if(filterStr.length() == 0) {
				for(Method m : methods) {
					System.out.println(qualifier.matcher(m.toString()).replaceAll(""));
					results.append(qualifier.matcher(m.toString()).replaceAll("") + "\n");
				}
				for(Constructor<?> ctor : ctors) {
					results.append(qualifier.matcher(ctor.toString()).replaceAll("") + "\n");
				}
			} else {
				for(Method m : methods) {
					if(m.toString().indexOf(filterStr) != -1)
						results.append(qualifier.matcher(m.toString()).replaceAll("") + "\n");
				}
				for(Constructor<?> ctor : ctors) {
					if(ctor.toString().indexOf(filterStr) != -1)
						results.append(qualifier.matcher(ctor.toString()).replaceAll("") + "\n");
				}
			}
		}
	}
	
	public Ex9(){
		NameL nameListener = new NameL();
		name.addActionListener(nameListener);
		JPanel top = new JPanel(new FlowLayout());
		top.add(name);
		top.add(filter);
		add(BorderLayout.NORTH, top);
		add(new JScrollPane(results));
	}

	public static void main(String[] args) {
		SwingConsole.run(new Ex9(), 700, 400);
	}

}
